﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ePlanet.SingleWell.Services;
using DreamBuilder.Core.Container;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.DataAccess;
using System.Data;
using System.Text;

namespace Web.HttpHandles
{
    /// <summary>
    /// GetTreeDataHandler 的摘要说明
    /// </summary>
    public class GetTreeDataHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            StringBuilder resultStr = new StringBuilder("[");
            if (!string.IsNullOrEmpty(context.Request.QueryString["treeType"]) && context.Request.QueryString["treeType"].ToLower() == "singlewelltree")
            {
                int page = int.Parse(context.Request.QueryString["page"]);
                int pageSize = int.Parse(context.Request.QueryString["pageSize"]);
                bool isPage = bool.Parse(context.Request.QueryString["isPage"]);
                string pid = context.Request.QueryString["id"];
                string searchLevel = context.Request.QueryString["searchLevel"];
                string searchParam = context.Request.QueryString["searchParam"];
                string jsonFormat = "{{\"id\": \"{0}\", \"name\": \"{1}\", \"pId\": \"{2}\", \"catelogsort\": \"{3}\", \"iswellcode\": {4}, \"count\": {5}, \"page\": 1, \"pageSize\": 5, \"isParent\": {6}, \"open\": {7}, \"wellCount\": {8}}},";
                WellCatalogDAL wellCatalogDAL = new WellCatalogDAL();
                DataTable oDataTable = wellCatalogDAL.GetWellCatalogByPage(page, pageSize, pid, isPage, searchLevel, searchParam);
                if (oDataTable != null)
                {
                    foreach (DataRow row in oDataTable.Rows)
                    {
                        int ccount = int.Parse(row["CCOUNT"].ToString());
                        int wellCount = int.Parse(row["WELLCOUNT"].ToString());
                        string isParent = ccount > 0 ? "true" : "false";
                        string open = string.IsNullOrEmpty(searchParam)?"false":"true";
                        resultStr.Append(string.Format(jsonFormat, row["WELLCATALOGID"].ToString(), row["CATALOGDESCRIPT"].ToString(), row["PARENTID"].ToString(), row["CATELOGSORT"].ToString(), int.Parse(row["ISWELLCODE"].ToString()), ccount, isParent, open, wellCount));
                    }
                    if (resultStr.Length > 1)
                    {
                        resultStr = resultStr.Remove(resultStr.Length - 1, 1);
                    }
                }
            }
            else
            { 
                
            }
            resultStr.Append("]");
            context.Response.ContentType = "text/json";
            context.Response.Write(resultStr.ToString());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}